package com.peteralbus.service.impl;

import com.peteralbus.entity.EarthquakeInfo;
import com.peteralbus.entity.Hospital;
import com.peteralbus.entity.IntensityLine;
import com.peteralbus.mapper.EarthquakeInfoMapper;
import com.peteralbus.mapper.HospitalMapper;
import com.peteralbus.service.EarthquakeInfoService;
import com.peteralbus.service.HospitalService;
import com.peteralbus.service.IntensityLineService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * The type Hospital service.
 *
 * @author PeterAlbus
 */
@Service
public class HospitalServiceImpl implements HospitalService {

    private HospitalMapper hospitalMapper;
    private EarthquakeInfoService earthquakeInfoService;
    private IntensityLineService intensityLineService;

    @Autowired
    public void setIntensityLineService(IntensityLineService intensityLineService) {
        this.intensityLineService = intensityLineService;
    }

    @Autowired
    public void setEarthquakeInfoService(EarthquakeInfoService earthquakeInfoService) {
        this.earthquakeInfoService = earthquakeInfoService;
    }

    /**
     * Sets hospital mapper.
     *
     * @param hospitalMapper the hospital mapper
     */
    @Autowired
    public void setHospitalMapper(HospitalMapper hospitalMapper) {
        this.hospitalMapper = hospitalMapper;
    }

    @Override
    public List<Hospital> findAllHospital() {
        return hospitalMapper.selectList(null);
    }

    @Override
    public List<Hospital> getAllNearHospital(Double lon, Double lat, Double lonDistance, Double latDistance) {
        List<Hospital> hospitalList=new ArrayList<>();
        int i=1;
        //防止找不到医院，依次扩大范围
        while (hospitalList.size()==0){
            hospitalList=hospitalMapper.getAllNearHospital(lon, lat, lonDistance*i, latDistance*i);
            i++;
        }
        return hospitalList;
    }

    @Override
    public List<Hospital> getAllNearHospitalById(long id) {
        EarthquakeInfo earthquakeInfo = earthquakeInfoService.getEarthquakeInfoById(id);
        List<IntensityLine> list = intensityLineService.getIntensityLineByEarthquakeId(id);
        if (list.size() == 0)
            return getAllNearHospital(earthquakeInfo.getLongitude(), earthquakeInfo.getLatitude(), 1.0, 1.0);
        else {
            Double lonMax = 0.0, latMax = 0.0;
            for (IntensityLine intensityLine : list) {
                if (intensityLine.getLongRadius() > lonMax) lonMax = intensityLine.getLongRadius()/111;
                if (intensityLine.getShortRadius() > latMax) latMax = intensityLine.getShortRadius()/111;
            }
            return getAllNearHospital(earthquakeInfo.getLongitude(), earthquakeInfo.getLatitude(), lonMax, latMax);
        }
    }
}
